/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package beans;

import general.interfaces.DataSessionInterface;
import general.util.MyGeneralUtil;
import general.util.MyPassDataUtil;
import general.util.MySecurityUtil;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import jpa.entity.Obra;
import jpa.entity.User;

/**
 *
 * @author isaias
 */
@ManagedBean
@SessionScoped
public class DataSessionManagedBean implements Serializable, DataSessionInterface{
     private final String SUCESS_LOGIN = "Seja bem vindo!";
     private final String ERRO_LOGIN = "Dados inválidos!";
     private User currentUser = new User();
     private Obra currentObra = new Obra();

    /** Creates a new instance of DataSessionManagedBean */
    public DataSessionManagedBean() {
    }

    public User getCurrentUser() {
        return currentUser;
    }

    public void setCurrentUser(User currentUser) {
        this.currentUser = currentUser;
    }

     public String login() {
        //this.loggedIn = false;
        try {

            currentUser = MyGeneralUtil.login(currentUser.getLogin(), MySecurityUtil.md5(currentUser.getPassword()));

            if (currentUser != null) {
                 selectObra();
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, SUCESS_LOGIN, null));
                return MainMenuBean.homePage(currentUser);
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ERRO_LOGIN, null));
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao logar (" + ex.getMessage() + ")", null));
        }

        logout();

        return null;

    }



    private void selectObra(){
        for(Obra obra : currentUser.getObras()){
            currentObra = obra;
        }
    }

    public String logout() {
        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(true);
        session.invalidate();
        return "/index";
    }

    public Obra getCurrentObra() {
        return currentObra;
    }

    public void setCurrentObra(Obra currentObra) {
        this.currentObra = currentObra;
    }


}
